<?php

class PageLoad {

	/**
	 * String Valid username
	 */
	private $realUserName = "Admin";
	
	 
	 /**
	 * String Valid password
	 */
	private $realPassword = "Password";
	
	/**
	 * String Valid password
	 */
	private $realPasswordScrambled = "g5Hdf8S4";

	/**
	 * String Decides what html gets rendered
	 */
	private $loginState = "notLoggedIn";
	
	/**
	 * String HTML
	 */
	private $loggedInStatus;

	/**
	 * String contains the username that was used in the latest login attempt
	 */
	private $lastUsername = "";
	
	/**
	 * String contains the appropriate login message for the user
	 */
	private $message;
	
	private $notLoggedIn = "Ej inloggad";
	private $loggedIn = "Inloggad";

	/**
	 * String HTML
	 */
	private $inputField;

	/**
	 * String HTML
	 */
	private $currentDate;

	/**
	 * String HTML
	 */
	private $form = "<form name='login' id='login' method='POST'>
					Användarnamn: 
					<input type='text' name='username' id='username' value='' class='text' maxlenght='20' />
					</br>
					Lösenord: 
					<input type='password' name='password' id='password' class='text' maxlenght='20' />
					</br>
					Håll mig inloggad: 
					<input type='checkbox' name='keepLoggedIn' value='Bike'>
					</br>
					<input type='submit' value='Logga in' />
					</form>";
		
	/**
	 * String HTML
	 */
	private $logoutButton = "<form name='logout' id='logout' method='POST'>
							<input type='submit' value='Logga ut'</input></form>";

	public function doAllTheStuff() {
		setlocale(LC_ALL, 'sv_SE', 'sv_SE.UTF-8', 'Swedish_Sweden.1252', 'WINDOWS-1252');
		
		$this -> checkLogin($this->realUserName, $this->realPassword);
		$this -> setFields($this-> loginState);
		$this -> currentDate = $this -> setClock();
		$this -> renderHTML();		
	}

	/**
	 * Checks whether the user tried to login 
	 * using a valid username/password combination
	 *
	 * @param $realUserName Valid username
	 * @param $realPassword Valid password
	 */
	private function checkLogin($realUserName, $realPassword) {
		assert($realUserName);
		assert($realPassword);

		if (strtoupper($_SERVER['REQUEST_METHOD']) == 'POST' && $_SESSION['loggedIn'] == 'true') {
			$_SESSION['loggedIn'] = 'false';
			$this -> loginState = "justLoggedOut";			
		} elseif(isset($_COOKIE["username"]) && isset($_COOKIE["password"])){
			if($this -> checkCookies() && $_SESSION['loggedIn'] != 'true'){
				$this -> loginState = "justLoggedInCookie";
				$_SESSION['loggedIn'] = 'true';
			} elseif($this -> checkCookies()) {
				$this -> loginState = "loggedIn";				
			} else{
				$this -> loginState = "badCookie";				
			}
		} elseif ($_SESSION['loggedIn'] == 'true'  &&  $this -> checkSession()) {
			$this -> loginState = "loggedIn";
		} elseif (isset($_POST['username']) && isset($_POST['password'])) {
			if ($_POST['username'] == $realUserName && $_POST['password'] == $realPassword) {
				if(isset($_POST['keepLoggedIn'])){
					$this -> loginState = "justLoggedInSetCookie";
					$this -> setCookie();							
				}
				else{
					$this -> loginState = "justLoggedIn";
				}
				$_SESSION["webbläsare"] = $_SERVER["HTTP_USER_AGENT"];		
				$_SESSION["ip"] = $_SERVER["REMOTE_ADDR"];
				$_SESSION['loggedIn'] = 'true';
			} elseif ($_POST['username'] != "" && $_POST['password'] == "") {
				$this -> loginState = "missingPassword";
			} elseif ($_POST['username'] == "" && $_POST['password'] != "") {
				$this -> loginState = "missingUsername";
			} elseif ($_POST['username'] == $realUserName && $_POST['password'] != $realPassword) {
				$this -> loginState = "wrongUsernameOrPassword";
			} elseif ($_POST['username'] != $realUserName&& $_POST['password'] == $realPassword) {
				$this -> loginState = "wrongUsernameOrPassword";
			} elseif ($_POST['username'] == "" && $_POST['password'] == "") {
				$this -> loginState = "missingUsername";
			}
		} else {
			$this -> loginState = "notLoggedIn";
		}
	}

	/**
	 * Returns true if there are valid cookies available
	 *  @return Boolean
	 */
	function checkCookies(){
		if(isset($_COOKIE["username"]) && isset($_COOKIE["password"])){
			if($_COOKIE["username"] == $this -> realUserName && 
			$_COOKIE["password"] == $this -> realPasswordScrambled){
				$cookieEndtime = file_get_contents("cookieExpiry.txt");
				if($cookieEndtime > time()){
					return true;	
				}
				else {
					return false;
				}
			}
		} else {
			return false;
		}				
	}
	
	/**
	 * Returns true if the session truly belongs to the user
	 *  @return Boolean
	 */
	function checkSession(){
		if($_SESSION["webbläsare"] == $_SERVER["HTTP_USER_AGENT"] && 
		$_SESSION["ip"] == $_SERVER["REMOTE_ADDR"]){
			return true;
		}
		else {
			return false;
		}
	}
	
	private function setCookie(){
		$endTime = time () + 60;
		file_put_contents("cookieExpiry.txt", $endTime);
		setcookie("username", $this -> realUserName, $endTime);
		setcookie("password", $this -> realPasswordScrambled, $endTime);
		
	}
	
	private function removeCookie(){
		// setcookie("username", $this -> realUserName, time()-60);
		// setcookie("password", $this -> realPassword, time()-60);		setcookie("username", "", time()-60);
		setcookie("password", "", time()-60);		// if (isset($_SERVER['HTTP_COOKIE'])) {
	    	// $cookies = explode(';', $_SERVER['HTTP_COOKIE']);
	    	// foreach($cookies as $cookie) {
		        // $parts = explode('=', $cookie);
		        // $name = trim($parts[0]);
		        // setcookie($name, "", time()-1000);
	    	// }	
		// }
	}

	/**
	 * @param $loginState Decides which messages gets echoed out
	 */	
	private function setFields($loginState) {
		assert($loginState);
		$this -> lastUsername = "";
		$this -> loggedInStatus = "";
		$this -> message = "";
		$this -> inputField = "";
		switch ($loginState) {
			case 'notLoggedIn' :
				$this -> loggedInStatus = "<h2>Ej Inloggad</h2>";
				$this -> inputField = $this -> form;
				break;
			case 'justLoggedIn' :
				$this -> loggedInStatus = "<h2>Admin är Inloggad</h2>";
				$this -> message = "Inloggning lyckades";
				$this -> inputField = $this -> logoutButton;
				break;
			case 'justLoggedInSetCookie' :
				$this -> loggedInStatus = "<h2>Admin är Inloggad</h2>";
				$this -> message = "Inloggning lyckades och vi kommer ihåg dig nästa gång";
				$this -> inputField = $this -> logoutButton;
				break;
			case 'justLoggedInCookie' :
				$this -> loggedInStatus = "<h2>Admin är Inloggad</h2>";
				$this -> message = "Inloggning lyckades med hjälp av cookies";
				$this -> inputField = $this -> logoutButton;
				break;
			case 'loggedIn' :
				$this -> loggedInStatus = "<h2>Admin är Inloggad</h2>";
				$this -> inputField = $this -> logoutButton;
				break;
			case 'justLoggedOut' :
				$this -> loggedInStatus = "<h2>Ej Inloggad</h2>";
				$this -> message = "Du har nu loggat ut";
				$this -> inputField = $this -> form;
				$this -> removeCookie();
				break;
			case 'badCookie' :
				$this -> loggedInStatus = "<h2>Ej Inloggad</h2>";
				$this -> message = "Felaktig information i cookie";
				$this -> inputField = $this -> form;
				$this -> removeCookie();
				break;
			case 'missingUsername' :
				$this -> loggedInStatus = "<h2>Ej Inloggad</h2>";
				$this -> message = "Användarnamn saknas";
				$this -> inputField = $this -> form;
				break;
			case 'missingPassword' :
				$this -> lastUsername = $_POST['username'];
				$this -> loggedInStatus = "<h2>Ej Inloggad</h2>";
				$this -> message = "Lösenord saknas";
				$this -> inputField = $this -> form;
				break;
			case 'wrongUsernameOrPassword' :
				$this -> lastUsername = $_POST['username'];
				$this -> loggedInStatus = "<h2>Ej Inloggad</h2>";
				$this -> message = "Fel användarnamn och/eller lösenord";
				$this -> inputField = $this -> form;
				break;
			case 'default' :
				break;
		}
	}

	/**
	 * Renders the page
	 */
	private function renderHTML() {
		if ($this -> loginState == "notLoggedIn" || 
		$this -> loginState == "justLoggedOut" || 
		$this -> loginState == "missingUsername" || 
		$this -> loginState == "missingPassword" || 
		$this -> loginState == "wrongUsernameOrPassword") {				
		echo "<!DOCTYPE HTML>
			<html>
				<head>
					<title>Laboration. Inte inloggad</title>
					<meta http-equiv='Content-Type' content='text/html;charset=utf-8'>
				</head>
				<body><h1> Laboration ep222fj </h1>" . $this -> loggedInStatus . "
					<br><p> " . $this -> message . " </p>
					<form name='login' id='login' method='POST'>
						Användarnamn: 
						<input type='text' name='username' id='username' value='" . $this -> lastUsername . "' class='text'>
						<br>
						Lösenord: 
						<input type='password' name='password' id='password' class='text'>
						<br>
						Håll mig inloggad: <input type='checkbox' name='keepLoggedIn' id='keepLoggedIn'>
						<br>
						<input type='submit' value='Logga in' />
					</form>
					<p>
					<br> " . $this -> currentDate . "
					</p>
				</body>
			</html>";
		} else {
			echo "<!DOCTYPE HTML>
				<html>
					<head>
						<title>Laboration. Inloggad</title>
						<meta http-equiv='Content-Type' content='text/html;charset=utf-8'>
					</head>				
					<body> 
						<h1> Laboration ep222fj </h1>
						<p>" . $this -> loggedInStatus . "
						<br> " . $this -> message . "
						<br> " . $this -> inputField . "
						<br> " . $this -> currentDate . "
						</p>
					</body>
				</html>";
		}
	}

	/**
	 * @return String with current time and date
	 */
	private function setClock() {
		setlocale(LC_TIME, 'sv_SE', 'sv_SE.UTF-8', 'Swedish_Sweden.1252', 'WINDOWS-1252');
		//$this -> currentDate = strftime("%A, den %d %B år %Y. Klockan är [%H:%M:%S]");
		return strftime("%A, den %d %B år %Y. Klockan är [%H:%M:%S]");
	}

}

/**
 * Använder 
 * http://stackoverflow.com/questions/2310558/how-to-delete-all-cookies-of-my-website-in-php
 * i removeCookie
 */